package com.jiesen.base.modules.login.jsRole.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiesen.base.baseDao.BaseServiceImpl;
import com.jiesen.base.modules.login.jsRole.mapper.JsRoleDao;
import com.jiesen.base.modules.login.jsPermission.mapper.PermissionDao;
import com.jiesen.base.modules.login.jsRole.model.JsRole;
import com.jiesen.base.modules.login.jsPermission.model.Permission;
import com.jiesen.base.modules.login.jsRole.service.JsRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
public class JsRoleServiceImpl extends BaseServiceImpl<JsRoleDao, JsRole> implements JsRoleService {

    @Autowired
    private PermissionDao permissionDao;

    //根据用户id查询用户所拥有的角色
    @Override
    public List<JsRole> findRoleByUserId(Integer id) {
        //查询角色信息
        return baseMapper.findRoleByUserId(id);
    }

    //根据用户id查询用户所拥有的角色和权限信息(列表)
    @Override
    public List<JsRole> findRolePByUserId(Integer id) {
        //查询角色信息
        List<JsRole> roles = baseMapper.findRoleByUserId(id);
        if (roles == null) {
            return null;
        }
        //查询角色的权限信息
        for (JsRole role : roles) {
            List<Permission> permissions = permissionDao.findPermissionByRoleId(role.getId());

            role.setPermissions(permissions);
        }
        return roles;
    }

    //根据角色Id查询角色以及角色拥有的权限信息
    @Override
    public JsRole getByIdAndPermission(Serializable id) {
        JsRole jsRole = super.getById(id);
        List<Permission> permissions = permissionDao.findPermissionByRoleId(id);
        jsRole.setPermissions(permissions);
        return jsRole;
    }

    //根据分校id查询所有角色信息
    @Override
    public List<JsRole> findAll(Integer breandId) {
        QueryWrapper<JsRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("branch_id",breandId);
        return baseMapper.selectList(queryWrapper);
    }

    //角色权限修改
    @Override
    public boolean updataRolePermission(Integer rid, List<Integer> pids) {
        baseMapper.deletePermissionByRoleId(rid);
        for (Integer pid : pids) {
            baseMapper.insertPermissionByRoleId(rid, pid);
        }
        return true;
    }

    //删除角色同时删除关联表
    @Override
    @Transactional
    public boolean removeById(Serializable id) {
        baseMapper.deletePermissionByRoleId(id);
        return super.removeById(id);
    }

}
